package com.hqyj.sale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.goods.entity.Goods;
import com.hqyj.goods.service.GoodsService;
import com.hqyj.sale.dto.SaleInfo;
import com.hqyj.sale.entity.Sale;
import com.hqyj.sale.mapper.SaleMapper;
import com.hqyj.sale.service.SaleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.storage.entity.Storage;
import com.hqyj.utils.PageUtil;
import com.hqyj.utils.ResultUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sdx2009
 * @since 2022-09-30
 */
@Service
public class SaleServiceImpl extends ServiceImpl<SaleMapper, Sale> implements SaleService {

    @Autowired
    private GoodsService goodsService;

    @Transactional
    @Override
    public ResultUtils joinSale(SaleInfo saleInfo) {
        boolean b = goodsService.updateGoodsNums(saleInfo.getGoodsId(), saleInfo.getGoodsNums() - saleInfo.getSaleGoodsNums());
        if (b){
            Sale sale = new Sale();
            BeanUtils.copyProperties(saleInfo,sale);
            sale.setSaleGoodsPriceCount(saleInfo.getSaleGoodsPrice() * saleInfo.getSaleGoodsNums());
            if (this.save(sale)){
                return new ResultUtils(200,"出售成功！",null);
            }
        }
        return new ResultUtils(500,"出售失败！",null);
    }

    @Override
    public ResultUtils saleIndex(SaleInfo saleInfo) {
        Page<Sale> page = new Page<>(saleInfo.getPage(),saleInfo.getRow());
        QueryWrapper<Sale> qw = new QueryWrapper<>();
        qw.like(saleInfo.getSaleGoodsName() != null && !saleInfo.getSaleGoodsName().equals(""),"sale_goods_name",saleInfo.getSaleGoodsName());
        Page<Sale> pageList = this.page(page, qw);
        PageUtil<Sale> pageUtil = new PageUtil<>();
        pageUtil.setData(pageList.getRecords());
        pageUtil.setTotal(pageList.getTotal());
        pageUtil.setTotalPage(pageList.getPages());
        return new ResultUtils(200,"",pageUtil);
    }
}
